<template>
  <div class="mod-config">
    <el-button-group style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
      <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
      <el-button type="primary" v-if="permissions.eims_savemoneycard_add" @click="addOrUpdateHandle('','add')">新增</el-button>
      <el-button type="primary" v-if="permissions.eims_savemoneycard_batchadd" @click="addOrUpdateHandle('','batchAdd')">批量新增</el-button>
      <el-button type="primary" v-if="permissions.eims_batchstatus_open" @click="batchOpenStatus">批量启用</el-button>
      <el-button type="primary" v-if="permissions.eims_batchstatus_close" @click="batchCloseStatus">批量停用</el-button>
      <el-button type="primary" v-if="permissions.eims_savemoneycard_batchdel" @click="batchDel">批量删除</el-button>
      <el-button type="primary"  @click="balanceReset">普通储值卡余额清零</el-button>
      <el-button type="primary" @click="printInfo">导出成Excel</el-button>
    </el-button-group>
    <el-upload ref="upload" class="upload-demo"
      action="/eims/saveMoneyCard/upload"
      :headers="headers"
      :on-success="successHandle"
      :on-error="errorHandle"
      :show-file-list="false">
      <el-button type="primary">导入Excel表</el-button>
    </el-upload>

      <el-form inline @keyup.enter.native="searchHandle" style="margin-top: 5px;">
        <el-form-item label="储值卡号" prop="cardNum">
          <el-input v-model="dataForm.cardNum" placeholder="储值卡号"></el-input>
        </el-form-item>
        <el-form-item label="建卡人工号" prop="workNumber">
          <el-input v-model="dataForm.workNumber" placeholder="建卡人工号"></el-input>
        </el-form-item>
        <el-form-item label="建卡人姓名" prop="username">
          <el-input v-model="dataForm.username" placeholder="建卡人姓名"></el-input>
        </el-form-item>
        <el-form-item label="绑定会员姓名" prop="customerName">
          <el-input v-model="dataForm.customerName" placeholder="绑定会员姓名"></el-input>
        </el-form-item>
        <el-form-item label="发放部门" prop="saleDeptId">
          <el-select v-model="dataForm.saleDeptId" placeholder="请选择部门">
            <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="身份证" prop="idNumber">
          <el-input v-model="dataForm.idNumber" placeholder="身份证"></el-input>
        </el-form-item>
        <el-form-item label="建卡日期">
          <el-row>
            <el-col :span="11">
              <el-date-picker v-model="dataForm.createTimeMin" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
            </el-col>
            <el-col class="line" :span="2" style="text-align: center;">-</el-col>
            <el-col :span="11">
              <el-date-picker v-model="dataForm.createTimeMax" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="dataForm.phone" placeholder="手机号码"></el-input>
        </el-form-item>
      </el-form>

      <div class="avue-crud">
        <el-table :data="dataList" height="calc(100vh - 215px)" border v-loading="dataListLoading" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" icon="el-icon-edit" @click="getInfo(scope.row.id)">详细</el-button>
              <el-button v-if="permissions.eims_savemoneycard_edit" type="text" icon="el-icon-edit" @click="topUpOrWithdrawMoney(scope.row.id)">充值</el-button>
              <el-button v-if="permissions.eims_savemoneycard_edit" type="text" icon="el-icon-edit" @click="addOrUpdateHandle(scope.row.id,'update')">修改</el-button>
              <el-button v-if="permissions.eims_savemoneycard_del" type="text" icon="el-icon-delete"
                @click="deleteHandle(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" :formatter="formatter" width="66">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status == 1" type="text" @click="editStatus(scope.row.id)">启用</el-button>
              <el-button v-if="scope.row.status == 0" type="text" @click="editStatus(scope.row.id)">停用</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="cardNum" label="储值卡号"></el-table-column>
          <el-table-column prop="customerName" label="绑定会员"></el-table-column>
          <el-table-column prop="phone" label="手机号码"></el-table-column>
          <el-table-column prop="balance" label="卡内金额"></el-table-column>
          <el-table-column prop="workNumber" label="创建人工号"></el-table-column>
          <el-table-column prop="username" label="创建人姓名"></el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="166"></el-table-column>
          <el-table-column prop="lastCustomerTime" label="最后一次绑定会员的时间"></el-table-column>
          <el-table-column prop="saleDeptName" label="发放部门"></el-table-column>
          <el-table-column prop="deptName" label="建卡部门"></el-table-column>
        </el-table>
      </div>

      <div class="avue-crud__pagination">
        <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next"></el-pagination>
      </div>
      <table-form v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></table-form>
      <table-form2 v-if="infoVisible" ref="info" @refreshDataList="getDataList"></table-form2>
      <table-form3 v-if="topUpOrWithdrawMoneyVisible" ref="topUpOrWithdrawMoney" @refreshDataList="getDataList"></table-form3>
  </div>
</template>

<script>
  import {
    fetchList,
    delObj,
    editStatusById,
    batchOpenStatusByIds,
    batchCloseStatusByIds,
    batchRemoveByIds,
    moneyReset,
    saveCardExportToExcel
  } from "@/api/eims/savemoneycard"
  import TableForm from "./savemoneycard-form"
  import TableForm2 from "./info"
  import TableForm3 from "./topUpOrWithdrawMoney"
  import { mapGetters } from "vuex"
  import { filterParams } from "@/util/tools"
  import { getDeptInfo } from "@/api/admin/dept"
  import store from '@/store'

  export default {
    data() {
      return {
        headers: {
          'Authorization': 'Bearer ' + store.getters.access_token,
        },
        tableDataAmount: [],
        dataForm: {
          cardNum: '',
          workNumber: '',
          phone: '',
          username: '',
          customerName: '',
          customerId: '',
          saleDeptId: '',
          idNumber: '',
          createTimeMin: '',
          createTimeMax: ''
        },
        deptOptions: [],
        dataList: [],
        searchShow: true,
        pageIndex: 1,
        pageSize: 100,
        totalPage: 0,
        dataListLoading: false,
        addOrUpdateVisible: false,
        topUpOrWithdrawMoneyVisible: false,
        infoVisible: false,
        ids: []
      };
    },
    components: {
      TableForm,
      TableForm2,
      TableForm3
    },
    created() {
      this.getDataList();
      this.getDeptList();
    },
    computed: {
      ...mapGetters(["permissions"])
    },
    methods: {
      //  查询数据
      searchHandle() {
        this.pageIndex = 1
        this.getDataList()
      },
      // 获取数据列表
      getDataList() {
        this.dataListLoading = true;
        let params1 = {
          current: this.pageIndex,
          size: this.pageSize
        }
        let params2 = filterParams(this.dataForm)
        fetchList(Object.assign(params1, params2)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.getDataList();
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val;
        this.getDataList();
      },
      // 新增 / 修改
      addOrUpdateHandle(id, type) {
        this.addOrUpdateVisible = true;
        let data = {
          id: id,
          type: type
        };
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(data);
        });
      },
      // 充值 / 提现
      topUpOrWithdrawMoney(id) {
        this.topUpOrWithdrawMoneyVisible = true;
        this.$nextTick(() => {
          this.$refs.topUpOrWithdrawMoney.init(id);
        });
      },
      //详细按钮
      getInfo(id) {
        this.infoVisible = true;
        this.$nextTick(() => {
          this.$refs.info.init(id);
        });
      },
      // 删除
      deleteHandle(id) {
        this.$confirm("是否确认删除ID为" + id, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delObj(id);
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success("删除成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      searchChange() {
        let params1 = filterParams(this.dataForm);
        let params2 = {
          current: this.pageIndex,
          size: this.pageSize
        };
        fetchList(Object.assign(params2, params1)).then(response => {
          if(response.data.code == '0'){
            this.dataList = response.data.data.records
            this.totalPage = response.data.data.total
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 搜索清空
      searchReset() {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
        }
      },
      handleSearchShow() {
        this.searchShow = !this.searchShow;
      },
      // 刷新回调
      refreshChange() {
        this.getDataList(this.page);
      },
      formatter(row, column, cellValue, index) {
        return index === 1 ? "启用" : "停用";
      },
      editStatus(id) {
        editStatusById(id).then(response => {
          if(response.data.code == '0'){
            this.$message.success("修改状态成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      batchOpenStatus() {
        // 清除选中状态
        //this.$refs.multipleTable.clearSelection()
        batchOpenStatusByIds(this.ids).then(response => {
          if(response.data.code == '0'){
            this.tableDataAmount = []
            this.$message.success("批量启用成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      batchCloseStatus() {
        batchCloseStatusByIds(this.ids).then(response => {
          if(response.data.code == '0'){
            this.$message.success("批量停用成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      batchDel() {
        batchRemoveByIds(this.ids).then(data => {
          if(response.data.code == '0'){
            this.$message.success("批量删除成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      balanceReset(){
        moneyReset().then(response =>{
          if(response.data.code == '0'){
            this.$message.success("普通储值卡余额清零成功")
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // 选择事件 得到选中的数据
      handleSelectionChange(data) {
        let list = []
        this.tableDataAmount = data
        data.forEach(item => {
          list.push(item.id)
        })
        this.ids = list
      },
      getDeptList() {
        getDeptInfo().then(response => {
          if(response.data.code == '0'){
            let result = response.data.data
            let list = []
            result.forEach(item => {
              list.push({
                value: item.id,
                label: item.name
              })
            })
            this.deptOptions = list
          }else{
            this.$message.error(response.data.msg)
          }
        })
      },
      // excel上传成功
      successHandle(response, file, fileList){
        if(response.code == 1){
          this.$message.error(response.msg)
          this.getDataList();
        }else{
          this.$message.success('上传成功')
          this.getDataList();
        }
      },
      // excel上传失败
      errorHandle(err, file, fileList){
        this.$message.error(err)
      },
      //excel模式导出
      printInfo() {
        let params2 = filterParams(this.dataForm)
        saveCardExportToExcel(params2).then(response => {
          var blob = new Blob([response.data], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          });
          var reader = new FileReader();
          reader.readAsDataURL(blob);
          reader.onload = function(e) {
            var a = document.createElement('a');
            a.download = "储值卡信息.xlsx";
            a.href = URL.createObjectURL(blob);
            a.click();
          }
        })
      },
    }
  };
</script>
